package util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by gamy on 2017/7/16.
 */
public class StringUtil {
    public static String getColumnName(String str) {
        if (str.contains("INT") ||
                str.contains("DATE") ||
                str.contains("TEXT") ||
                str.contains("CHAR") ||
                str.contains("FLOAT") ||
                str.contains("NOT NULL")
                ) {
            String[] arr = str.trim().split("\\s+");
            if (arr != null && arr.length > 0) {
                return arr[0];
            }
        }
        return null;
    }

    public static String getTableName(String str) {
        if (str.contains("CREATE TABLE")) {
            String[] arr = str.split("\\s+");
            if (arr != null && arr.length > 0) {
                return arr[arr.length - 1];
            }
        }
        return null;
    }


    public static String underline2Camel(String line, boolean smallCamel) {
        if (line == null || "".equals(line)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Pattern pattern = Pattern.compile("([A-Za-z\\d]+)(_)?");
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(smallCamel && matcher.start() == 0 ? Character.toLowerCase(word.charAt(0)) : Character.toUpperCase(word.charAt(0)));
            int index = word.lastIndexOf('_');
            if (index > 0) {
                sb.append(word.substring(1, index).toLowerCase());
            } else {
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }

    public static String makeStringLowerOrUpper(String string, int index, boolean upper) {
        char[] chars = string.toCharArray();
        if (chars[index] >= 'A' && chars[index] <= 'Z' && !upper) {
            chars[index] += ('a' - 'A');
        } else if (chars[index] >= 'a' && chars[index] <= 'z' && upper) {
            chars[index] += ('A' - 'a');
        }
        return new String(chars);
    }

    public static void writeFile(String s, String path) {
        try {

            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream stream = new FileOutputStream(file);
            stream.write(s.getBytes(), 0, s.length());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
